package org.springblade.modules.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.modules.admin.service.WeChatDialogueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author Jackey
 * @date 2022年05月09日 15:17
 */
@Slf4j
@Service
public class WeChatDialogueServiceImpl implements WeChatDialogueService {

	/**
	 * 模板消息字体颜色
	 */
	private static final String TEMPLATE_FRONT_COLOR = "#32CD32";
	private static final String TEMPLATE_KEY_FIRST = "first";
	private static final String TEMPLATE_KEY_REMARK = "remark";

	private static final String REPAIR_MINI_PROGRAM_APPID = "wxb8dc0f5451620604";

	@Autowired
	protected WxMpConfigStorage configStorage;
	@Autowired
	protected WxMpService wxMpService;


	@Override
	public Boolean sendMsg(String openid, String templateId, Map<String, String> templateData) {
		if (ObjectUtil.isEmpty(templateData) || StrUtil.isEmpty(openid) || StrUtil.isEmpty(templateId)) {
			throw new ServiceException("数据不可为空");
		}
//		if (!templateData.containsKey(TEMPLATE_KEY_FIRST) || !templateData.containsKey(TEMPLATE_KEY_REMARK)) {
//			throw new ServiceException("map数据必须包含first和remark");
//		}
		WxMpTemplateMessage orderPaySuccessTemplate = WxMpTemplateMessage.builder().build();
		orderPaySuccessTemplate.setToUser(openid);
		orderPaySuccessTemplate.setTemplateId(templateId);

		//维保小程序跳转
		if (templateData.containsKey("params")) {
			orderPaySuccessTemplate.setMiniProgram(new WxMpTemplateMessage.MiniProgram(REPAIR_MINI_PROGRAM_APPID, templateData.get("params"), false));
			templateData.remove("params");
		}

		for (String key : templateData.keySet()) {
			orderPaySuccessTemplate.addData(new WxMpTemplateData(key, templateData.get(key), TEMPLATE_FRONT_COLOR));
		}
		try {
			String templateMsg = wxMpService.getTemplateMsgService()
				.sendTemplateMsg(orderPaySuccessTemplate);
			log.info("维修模板发送结果状态......" + templateMsg);
		} catch (WxErrorException e) {
//			log.error(e.getMessage());
		}

		return Boolean.TRUE;
	}
}
